package cn.walmt.service;

import cn.walmt.dto.Store;
import cn.walmt.entity.Post;
import cn.walmt.mapper.PostMapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.GsonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class StoreService {

    @Autowired
    private PostMapper postMapper;

    public String getStoreByPostId(Integer postId) {
        if (postId == null) {
            return GsonUtil.getErrorJson("postId不存在！");
        }
        Post post = postMapper.selectByPrimaryKey(postId);
        if (post == null) {
            return GsonUtil.getErrorJson("不存在该店！");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("label", post.getStore());
        map.put("lng", post.getLongitude());
        map.put("lat", post.getLatitude());
        return GsonUtil.getSuccessJson(map);
    }

    /**
     * 按地区分类，获取地区经纬以及该地区下的店及其店的经纬度
     *
     * @return
     */
    public String getAllStores(String keyword) {

        if (keyword == null) {
            return GsonUtil.getErrorJson("请输入搜索内容！");
        }
        keyword = keyword.replaceAll("\\\\", "\\\\\\\\").replaceAll("%", "\\\\%").replaceAll("_", "\\\\_");
        List<Post> posts = postMapper.selectAllPosts(keyword);
        System.out.println(posts);

        List<Map<String, Object>> districtShops = new ArrayList<>();
        Map<String, Object> districtShop = null;
        String temp = "";
        List<Map<String, Object>> shopList = null;

        for (Post post : posts) {
            if (temp.equals(post.getDistrict())) {
                Map<String, Object> shop = new HashMap<>();
                shop.put("label", post.getStore());
                shop.put("lng", post.getLongitude());
                shop.put("lat", post.getLatitude());
                shopList.add(shop);
            } else {
                temp = post.getDistrict();

                districtShop = new HashMap<>();
                districtShops.add(districtShop);
                districtShop.put("area", post.getDistrict());
                districtShop.put("lng", post.getLongitude());
                districtShop.put("lat", post.getLatitude());

                shopList = new ArrayList<>();
                districtShop.put("shopList", shopList);
                Map<String, Object> shop = new HashMap<>();
                shop.put("label", post.getStore());
                shop.put("lng", post.getLongitude());
                shop.put("lat", post.getLatitude());
                shopList.add(shop);
            }
        }
        return GsonUtil.getSuccessJson(districtShops);
    }
}
